package com.tinusgraglin.enclusiv.ui.screens

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.tinusgraglin.enclusiv.R
import com.tinusgraglin.enclusiv.datalayer.EditedArticle
import com.tinusgraglin.enclusiv.ui.EnclusivViewModelFactory
import com.tinusgraglin.enclusiv.ui.viewmodel.NewArticleViewModel
import com.tinusgraglin.enclusiv.ui.theme.BlueMain
import com.tinusgraglin.enclusiv.ui.theme.EnclusivTheme
import com.tinusgraglin.enclusiv.ui.theme.PurpleMain
import kotlinx.coroutines.launch

class NewArticleActivity : ComponentActivity() {
    private val viewModel: NewArticleViewModel by viewModels {
        EnclusivViewModelFactory()
    }

    private var uploadedId: Long? = null
    private var editedArticle: EditedArticle? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            EnclusivTheme {
                NewArticleScreen()
            }
        }
    }

    override fun onBackPressed() {
//        if (uploadedId != null && editedArticle != null) {
//            Log.d("##DBG 56768", "HERE 8989")
//            setResult(Activity.RESULT_OK, Intent().putExtra("UPLOADED_ARTICLE", Pair(uploadedId, editedArticle)))
//        } else {
//            Log.d("##DBG 56768", "HERE 877")
//            setResult(Activity.RESULT_CANCELED)
//        }
        super.onBackPressed()
    }

    override fun onDestroy() {
//        if (uploadedId != null && editedArticle != null) {
//            Log.d("##DBG 56768", "HERE 89891")
//            setResult(Activity.RESULT_OK, Intent().putExtra("UPLOADED_ARTICLE", Pair(uploadedId, editedArticle)))
//        } else {
//            Log.d("##DBG 56768", "HERE 8770")
//            setResult(Activity.RESULT_CANCELED)
//        }
        super.onDestroy()
    }

    @Preview
    @Composable
    fun NewArticleScreen() {
        var title by rememberSaveable{ mutableStateOf("") }
        var textContent by rememberSaveable{ mutableStateOf("") }
        val scope = rememberCoroutineScope()

        Box(modifier = Modifier.fillMaxSize()) {
            Column {
                IconButton(
                    modifier = Modifier.align(Alignment.Start),
                    onClick = {
                        onBackPressed()
                    }
                ) {
                    Icon(
                        modifier = Modifier.size(20.dp),
                        painter = painterResource(R.drawable.back),
                        contentDescription = "Icon Button: Back",
                    )
                }

                LazyColumn (
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 10.dp)
                        .padding(top = 4.dp)
                ){
                    item {
                        OutlinedTextField(
                            modifier = Modifier
                                .fillMaxWidth()
                                .wrapContentHeight(),
                            value = title,
                            label = { Text(text = "Title") },
                            onValueChange = {
                                if (it.length > 200)
                                    it.take(200)
                                title = it
                            },
                            textStyle = TextStyle(fontSize = 20.sp, fontWeight = FontWeight.Bold)
                        )
                    }
                    item {
                        Spacer(Modifier.height(30.dp))
                    }
                    item {
                        BasicTextField(
                            modifier = Modifier
                                .border(
                                    width = 1.dp,
                                    brush = Brush.linearGradient(listOf(PurpleMain, BlueMain)),
                                    shape = RoundedCornerShape(10.dp)
                                )
                                .padding(horizontal = 10.dp, vertical = 20.dp)
                                .fillMaxWidth()
                                .wrapContentHeight(),
                            value = textContent,
                            onValueChange = {
                                textContent = it
                            },
                            textStyle = TextStyle(fontSize = 14.sp, fontStyle = FontStyle.Normal)
                        )
                    }
                }
            }
            Row(
                modifier = Modifier.align(Alignment.BottomEnd),
                verticalAlignment = Alignment.CenterVertically
            ) {
                IconButton(
                    enabled = title.isNotEmpty() && textContent.isNotEmpty(),
                    modifier = Modifier
                        .size(64.dp)
                        .padding(bottom = 10.dp, end = 10.dp)
                        .background(
                            brush = Brush.linearGradient(listOf(PurpleMain, BlueMain)),
                            shape = CircleShape
                        ),
                    onClick = {
                        val deferred = viewModel.upload(title, textContent, listOf())
                        scope.launch {
                            try {
                                uploadedId = deferred.await()
                                editedArticle = EditedArticle(viewModel.loggedInUserProfile.id, title, textContent, listOf())
                                Log.d("##DBG 5656", "uploaded id = ${uploadedId} ar = ${editedArticle != null}")
                                setResult(Activity.RESULT_OK, Intent().putExtra("UPLOADED_ARTICLE", Pair(uploadedId, editedArticle)))
                                this@NewArticleActivity.finish()
                            } catch (e: Exception) {
                                Log.d("##DBG 5656", "msg ${e.message}")
                                e.printStackTrace()
                            }
                        }
                    }
                ){
                    Icon(
                        painter = painterResource(R.drawable.upload),
                        contentDescription = "Icon Button: Upload",
                        modifier = Modifier.size(24.dp),
                        tint = Color.White
                    )
                }
            }
        }
    }
}